package com.scy.edu.mvcframework.servlet;

import com.scy.edu.mvcframework.annotations.*;
import com.scy.edu.mvcframework.pojo.Handler;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 司晨雨
 * @date 2020/5/30 11:26
 * @description
 */
public class lgDispatacherServlet extends HttpServlet {

    private Properties properties = new Properties();

    private List<String> classNames = new ArrayList<String>();

    private Map<String,Object> map = new HashMap<String,Object>();

    //private Map<String,Method> handlerMapping = new HashMap<String,Method>();
    private List<Handler> handlerMapping = new ArrayList<>();


    @Override
    public void init(ServletConfig config) throws ServletException {
        // 1 加载配置文件
        String contextConfigLocation = config.getInitParameter("contextConfigLocation");
        doLoadConfig(contextConfigLocation);
        // 2 扫描相关的类，扫描注解
        doScan(properties.getProperty("scanPackage"));

        // 3 初始化bean对象（实现ioc容器，基于注解）
        doInstance();

        // 4 实现依赖注入
        doAutoWired();

        // 5 构造一个HandlerMapping处理器映射器，将配置好的url和Method建立映射关系
        initHandlerMapping();

        System.out.println("lagou mvc 初始化完成....");

        // 等待请求进入，处理请求

    }



    private void doScan(String sachPackage) {
         String scanPackagePath = Thread.currentThread().getContextClassLoader().getResource("").getPath() + sachPackage.replaceAll("\\.", "/");
        scanPackagePath = scanPackagePath.replaceAll("%20"," ");
         File pack = new File(scanPackagePath);
         File[] files = pack.listFiles();
         for (File file:files){
             if(file.isDirectory()){
                 //递归
                 doScan(sachPackage + "." + file.getName());
             }else if(file.getName().endsWith(".class")){
                 String className = sachPackage + "." + file.getName().replaceAll(".class", "");
                 classNames.add(className);
             }
         }
    }

    private void doLoadConfig(String contextConfigLocation) {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void doAutoWired(){
        if(map.isEmpty())return;
        for (Map.Entry<String,Object> entry:map.entrySet()){
            Field[] declaredFields = entry.getValue().getClass().getDeclaredFields();
            for (int i = 0; i < declaredFields.length; i++) {
                Field declaredField = declaredFields[i];
                if(!declaredField.isAnnotationPresent(MyAutowired.class)){
                    continue;
                }
                MyAutowired annotation = declaredField.getAnnotation(MyAutowired.class);
                String beanName = annotation.value();
                if("".equals(beanName.trim())){
                    beanName = declaredField.getType().getName();
                }
                declaredField.setAccessible(true);
                try {
                    declaredField.set(entry.getValue(),map.get(beanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void initHandlerMapping() {
        if(map.isEmpty())return;
        for (Map.Entry<String,Object> entry:map.entrySet()){
            Class<?> aClass = entry.getValue().getClass();
            if(!aClass.isAnnotationPresent(MyController.class)){
                continue;
            }
            String baseUrl = "";
            if(aClass.isAnnotationPresent(MyRequestMapping.class)){
                MyRequestMapping annotation = aClass.getAnnotation(MyRequestMapping.class);
                baseUrl = annotation.value();
            }

            Method[] methods = aClass.getMethods();
            for (int i = 0; i < methods.length; i++) {
                Method method = methods[i];
                if(!method.isAnnotationPresent(MyRequestMapping.class))continue;;
                MyRequestMapping annotation = method.getAnnotation(MyRequestMapping.class);
                String methodUrl = annotation.value();
                String url = baseUrl + methodUrl;

                Handler handler = new Handler(entry.getValue(), method, Pattern.compile(url));

                Parameter[] parameters = method.getParameters();
                for (int j = 0; j < parameters.length; j++) {
                    Parameter parameter = parameters[j];
                    if(parameter.getType() == HttpServletRequest.class || parameter.getType() == HttpServletResponse.class){
                        handler.getParamIndexMapping().put(parameter.getType().getSimpleName(), j);
                    }else{
                        handler.getParamIndexMapping().put(parameter.getName(), j);
                    }
                }
                handlerMapping.add(handler);
            }
        }
    }

    private void doInstance() {
        try {
            if (classNames.size() == 0)
                return;
            for (int i = 0; i < classNames.size(); i++) {
                String className = classNames.get(i);
                Class<?> aClass = Class.forName(className);
                if (aClass.isAnnotationPresent(MyController.class)) {
                    String simpleName = aClass.getSimpleName();
                    String lowerFirst = lowerFirst(simpleName);
                    Object o = aClass.newInstance();
                    map.put(lowerFirst, o);
                } else if (aClass.isAnnotationPresent(MyService.class)) {
                    MyService annotation = aClass.getAnnotation(MyService.class);
                    String beanName = annotation.value();
                    if (!"".equals(beanName.trim())) {
                        map.put(beanName, aClass.newInstance());
                    } else {
                        beanName = lowerFirst(aClass.getSimpleName());
                        map.put(beanName, aClass.newInstance());
                    }
                    Class<?>[] interfaces = aClass.getInterfaces();
                    for (int j = 0; j < interfaces.length; j++) {
                        Class<?> anInterface = interfaces[j];
                        map.put(anInterface.getName(), aClass.newInstance());
                    }
                } else {
                    continue;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        doPost(req, res);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        Handler handler = getHandler(req);
        if(handler == null){
            res.getWriter().write("404 not found");
            return;
        }

        Class<?> aClass = handler.getController().getClass();
        String userName = req.getParameter("userName");
        if(aClass.isAnnotationPresent(MyController.class)){
            if(aClass.isAnnotationPresent(MySecurity.class)){
                MySecurity annotation = aClass.getAnnotation(MySecurity.class);
                String[] value = annotation.value();
                boolean flag = ArrayUtils.contains(value, userName);
                if(flag == false){
                    res.getWriter().write("userName is not found");
                    return;
                }
            }
            Method[] methods = aClass.getMethods();
            for (Method method : methods) {
                if(method.isAnnotationPresent(MySecurity.class)){
                    MySecurity annotation = method.getAnnotation(MySecurity.class);
                    String[] value = annotation.value();
                    boolean flag = ArrayUtils.contains(value, userName);
                    if(flag == false){
                        res.getWriter().write("userName is not found");
                        return;
                    }
                }
            }
        }

        Class<?>[] parameterTypes = handler.getMethod().getParameterTypes();
        Object[] paraValues = new Object[parameterTypes.length];
        Map<String, String[]> parameterMap = req.getParameterMap();
        for (Map.Entry<String,String[]> param:parameterMap.entrySet()){
            String value = StringUtils.join(param.getValue(), ",");
            if(!handler.getParamIndexMapping().containsKey(param.getKey())){
                continue;
            }
            Integer index = handler.getParamIndexMapping().get(param.getKey());
            paraValues[index] = value;
        }
        String requestSimpleName = HttpServletRequest.class.getSimpleName();
        String responseSimpleName = HttpServletResponse.class.getSimpleName();
        int requestIndex = handler.getParamIndexMapping().get(requestSimpleName); //0
        paraValues[requestIndex] = req;
        int responseIndex = handler.getParamIndexMapping().get(responseSimpleName); //1
        paraValues[responseIndex] = res;

        try {
            handler.getMethod().invoke(handler.getController(),paraValues);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }

    private Handler getHandler(HttpServletRequest req) {
        if(handlerMapping.isEmpty())return null;
        String url = req.getRequestURI();

        for (Handler handler:handlerMapping){
            Matcher matcher = handler.getPattern().matcher(url);
            if(!matcher.matches())continue;
            return  handler;
        }
        return null;

    }

    // 首字母小写方法
    public String lowerFirst(String str) {
        char[] chars = str.toCharArray();
        if('A' <= chars[0] && chars[0] <= 'Z') {
            chars[0] += 32;
        }
        return String.valueOf(chars);
    }
}
